package com.editso.haier.listener;

import com.editso.haier.base.Roles;
import com.editso.haier.base.Vips;
import com.editso.haier.configure.HaierConfigure;
import com.editso.haier.dao.RoleDao;
import com.editso.haier.dao.UserDao;
import com.editso.haier.dao.VipDao;
import com.editso.haier.entity.Role;
import com.editso.haier.entity.User;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class ApplicationEvent implements ApplicationListener<ApplicationStartedEvent> {

    @Override
    public void onApplicationEvent(ApplicationStartedEvent applicationStartedEvent) {
        ConfigurableApplicationContext context = applicationStartedEvent.getApplicationContext();
        HaierConfigure configure = context.getBean(HaierConfigure.class);
        RoleDao roleDao = context.getBean(RoleDao.class);
        VipDao vipDao = context.getBean(VipDao.class);
        UserDao userDao = context.getBean(UserDao.class);
        User user = new User();
        user.setName(configure.getAdminUserName());
        user.setPassword(configure.getAdminPassword());
        List<Role> roles = Arrays.stream(Roles.values())
                .map(role -> roleDao.findByName(role.getName()).orElse(role.getRole()))
                .collect(Collectors.toList());
        roleDao.saveAll(roles);
        for (Vips value : Vips.values()) {
            if (vipDao.existsById(value.getCode())) continue;
            vipDao.save(value.getVip());
        }
        user = userDao.findByName(user.getName()).orElse(user);
        userDao.save(user);
        user.getRoles().addAll(roles);
        userDao.save(user);
    }

}
